package service

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"syscall"
	healthUtil "zxs-micro-2/zxs-micro-healthutil/service"
	"zxs-micro-2/zxs-micro-proto/serverfindpb/serverfind"
	"zxs-micro-2/zxs-micro-serverfind-server/logic"
	"zxs-micro-2/zxs-micro-serverfind-server/report"
)

func InitServerFindService() {
	lis, _ := net.Listen("tcp", report.Addr)
	s := grpc.NewServer()
	//healthserver := health.NewServer()
	//healthserver.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_SERVING)
	//healthpb.RegisterHealthServer(s, healthserver)
	healthUtil.InitHealthService(s)
	serverfind.RegisterServerFindServiceServer(s, &ServerFindService{})
	var servErr = make(chan error)
	go func() {
		if err := s.Serve(lis); err != nil {
			servErr <- err
		}
	}()
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	select {
	case <-sigs:
		fmt.Println("服务发现关闭.....")
	case shuterr := <-servErr:
		fmt.Println(shuterr)
		fmt.Println("由于出现错误，服务发现关闭......")
	}
	os.Exit(0)
}

type ServerFindService struct {
	serverfind.UnimplementedServerFindServiceServer
}

func (s ServerFindService) AddServer(ctx context.Context,
	request *serverfind.AddServerRequest) (*serverfind.AddServerResponse, error) {

	return logic.AddNewServerLogic(ctx, request.ServerType, request.ServerPort, request.Protocol)
}

func (s ServerFindService) QueryServerListByType(ctx context.Context,
	request *serverfind.QueryServerListByTypeRequest) (*serverfind.QueryServerListByTypeResponse, error) {

	return logic.QueryServerListByTypeLogic(ctx, request.ServerType)
}

func (s ServerFindService) ServerDown(ctx context.Context,
	req *serverfind.ServerDownRequest) (*serverfind.ServerDownResponse, error) {
	logic.ServerDownLogic(ctx, req.ServerId)
	return new(serverfind.ServerDownResponse), nil
}

func (s ServerFindService) QueryServerListByIds(ctx context.Context,
	req *serverfind.QueryServerListByIdsRequest) (*serverfind.QueryServerListByIdsResponse, error) {

	return logic.QueryServerListByIdsLogic(ctx, req.Ids)
}
